<!--
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 * No deletion without permission, or be held responsible to law.
 * @author PR
-->
<template>
  <BasicModal v-bind="$attrs" :title="title" :ctype="type" :okText="t('确认')" @register="registerModal" :minHeight="300"
    :width="500" :showOkBtn="false" :showCancelBtn="false">
    <!--  @keyup.enter="showInfo" -->
    <div class="ml-4 mt-4">
      <a-textarea v-model:value="inputRef" :placeholder="`请扫描${placeholder}(鼠标聚焦到当前位置)`"
        style="height: 250px; width: 450px" @keyup.enter="showInfo" ref="ainput" />
      <a-row :gutter="[16, 16]" style="margin-top: 20px; height: 30px">
        <a-col :span="24">
          <div v-if="tips == '扫码成功' || tips == '数据校验通过！'">
            <p class="tips-success">{{ tips }}</p>
          </div>
          <div v-else>
            <p class="tips-error">{{ tips }}</p>
          </div>
        </a-col>
      </a-row>
      <a-row :gutter="[16, 16]" style="margin-top: 15px">
        <a-col :span="5" :offset="14">
          <a-button type="error" @click="clearText('1')">重新扫描</a-button>
        </a-col>
        <a-col :span="5">
          <a-button type="success" @click="endScan()">结束扫描</a-button>
        </a-col>
      </a-row>
    </div>

    <debugForm @register="registerDrawerdebug" @success="handleSuccess" />
    <beginWorkForm @register="registerDrawerbeginWork" @success="handleSuccess" />
    <endWorkForm @register="registerDrawerendWork" @success="handleSuccess" />
    <xiaJiForm @register="registerDrawerxiaJi" @success="handleSuccess" />
    <shangJiForm @register="registerDrawershangJi" @success="handleSuccess" />
    <notifyFirstCheckForm @register="registerDrawernotifyFirstCheck" @success="handleSuccess" />
    

    <ListSelect @success="handleSuccess" selectType="machineTaskSelect" :selectList="selectListRef" :checkbox="false"
      :queryParams="queryParams" @select="handlSelect" ref="listSelectRef" v-show="false" />


  </BasicModal>
</template>
<script lang="ts" setup>
  import { ref, nextTick } from 'vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useMessage } from '/@/hooks/web/useMessage';

  import { useModal } from '/@/components/Modal';
  import { useDrawer } from '/@/components/Drawer';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { extdBillImportData } from '/@/api/extd/bill/extdBill';
  import globalSetting from '/@/enums/globalSetting';

  import { ListSelect } from '/@/components/ListSelect';
  import { checkMachineBar } from '/@/api/m8/barcode/barcode';
  import debugForm from './barcodeForm/debugForm.vue';
  import beginWorkForm from './barcodeForm/beginWorkForm.vue';
  import endWorkForm from './barcodeForm/endWorkForm.vue';
  import xiaJiForm from './barcodeForm/xiaJiForm.vue';
  import shangJiForm from './barcodeForm/shangJiForm.vue';
  import notifyFirstCheckForm from './barcodeForm/notifyFirstCheckForm.vue';



  const [registerPrintModal, { openModal: openPrintModal }] = useModal();
  const [registerDrawerdebug, { openDrawer: openDrawerdebug }] = useDrawer();
  const [registerDrawerbeginWork, { openDrawer: openDrawerbeginWork }] = useDrawer();
  const [registerDrawerendWork, { openDrawer: openDrawerendWork }] = useDrawer();
  const [registerDrawernotifyFirstCheck, { openDrawer: openDrawernotifyFirstCheck }] = useDrawer();
  const [registerDrawerxiaJi, { openDrawer: openDrawerxiaJi }] = useDrawer();
  const [registerDrawershangJi, { openDrawer: openDrawershangJi }] = useDrawer();

  

  const emit = defineEmits(['success', 'register']);
  const { t } = useI18n('extd.bill.extdBill');
  const { showMessage, showMessageModal, createConfirm } = useMessage();
  let placeholder = ref < string > ('图纸和工牌');

  const enterCount = ref(0);
  let inputRef = ref < string > ('');
  let ainput = ref < any > (null);
  let title = ref < any > (null);
  let funcType = ref < any > (null);
  let queryData = ref({}); //扫码验证参数
  let shangJiData = ref < any > ({});;

  let queryParams = ref({});
  const selectListRef = ref < Recordable[] > ([]);
  let listSelectRef = ref < any > (null);

  // 提示信息
  let tips = ref < string > ('');

  const [registerModal, { setModalProps, closeModal }] = useModalInner((data) => {
    inputRef.value = '';
    tips.value = '';
    queryData.value = {};
    title.value = data.title;
    funcType.value = data.funcType;
    queryData.value.funcType = data.funcType;
    queryData.value.machineId = data.machineId;
    ainput.value.focus();
  });

  // 清空内容
  function clearText(flag) {
    inputRef.value = '';
    enterCount.value = 0;
    ainput.value.focus();
    queryData.value.barPic = '';
    queryData.value.barUser = '';
    if (flag == 1) {
      tips.value = '';
    }
    // console.log(ainput);
  }

  // 结束扫描
  async function endScan() {
    let lines = inputRef.value.split(/[(\r\n)\r\n]+/);
    lines.forEach((item, index) => {
      // 删除空项
      if (item === '') {
        lines.splice(index, 1);
      }
    });
    ainput.value.blur();

    // queryData.value.barPic = lines.filter((item) => {
    //   return item.startsWith('99-');
    // });
    // queryData.value.barUser = lines.filter((item) => {
    //   return item.startsWith('98-');
    // });
    lines.forEach((item) => {
      if (item.startsWith('98-')) {
        queryData.value.barUser = item;
      } else if (item.startsWith('99-')) {
        queryData.value.barPic = item;
      }
    });

    if (!queryData.value.barPic) {
      tips.value = '图纸条码不正确!';
      clearText('');
      return false;
    }
    if (!queryData.value.barUser) {
      tips.value = '用户条码不正确!';
      clearText('');
      return false;
    }

    let res = await checkMachineBar(queryData.value);

    if (res.data.errorMsg) {
      tips.value = res.data.errorMsg;
      clearText('');
      return false;
    } else {
      tips.value = '数据校验通过！';
    }
    if (queryData.value.funcType == 'debug') {
      openDrawerdebug(true, res.data)
    }
    if (queryData.value.funcType == 'beginWork') {
      openDrawerbeginWork(true, res.data)
    }

    if (queryData.value.funcType == 'endWork') {
      openDrawerendWork(true, res.data)
    }

    if (queryData.value.funcType == 'notifyFirstCheck') {
      openDrawernotifyFirstCheck(true, res.data)
    }

    if (queryData.value.funcType == 'xiaJi') {
      openDrawerxiaJi(true, res.data)
    }

    if (queryData.value.funcType == 'shangJi') {
      shangJiData.value = res.data
      selectListRef.value = []
      queryParams.value = {
        // 'orderPic.picno': res.data.orderPic.picno || '',
        // 'orderPic.picname': res.data.orderPic.picname || '',
        'orderPic.id': res.data.orderPic.id,
      }
      await nextTick();
      listSelectRef.value.openSelectModal();
    }

  }

  async function handlSelect(values) {
    if (values.length == 0) {
      showMessage(t('请先选择任务!'));
      return;
    }
    let item = values[0]

    if (item.taskStatus == '3') {
      createConfirm({
        title: `【${item.taskCode}】当前任务已完成,是否继续加工？`,
        iconType: 'info',//success
        cancelText: '取消',
        okText: '确定',
        onOk: async () => {
          let data = {
            ...shangJiData.value,
            oper: item.oper,
            task: item
          }
          openDrawershangJi(true,data)
        },
      });
    } else if (item.taskStatus == '2') {
      createConfirm({
        title: `【${item.taskCode}】当前任务正在其它机床加工,是否继续？`,
        iconType: 'info',//success
        cancelText: '取消',
        okText: '确定',
        onOk: async () => {
          let data = {
            ...shangJiData.value,
            oper: item.oper,
            task: item
          }
          openDrawershangJi(true,data)
        },
      });
    } else if (item.taskStatus == '9') {
      createConfirm({
        title: `【${item.taskCode}】当前任务已暂停,是否继续加工？`,
        iconType: 'info',//success
        cancelText: '取消',
        okText: '确定',
        onOk: async () => {
          let data = {
            ...shangJiData.value,
            oper: item.oper,
            task: item
          }
          openDrawershangJi(true,data)
        },
      });
    } else {
      let data = {
        ...shangJiData.value,
        oper: item.oper,
        task: item
      }
      openDrawershangJi(true,data)
    }

  }


  const showInfo = async () => {
    let lines = inputRef.value.split(/[(\r\n)\r\n]+/);
    lines.forEach((item, index) => {
      // 删除空项
      if (item === '') {
        lines.splice(index, 1);
      }
    });
    enterCount.value++;
    if (enterCount.value === 2) {
      endScan()
    }
  }

  function handleSuccess(data) {
    setTimeout(closeModal);
    emit('success', data);
  }

</script>

<style scoped>
  .ant-btn-error {
    /* margin-right: 10px; */
    float: right;
  }

  .ant-input {
    background: url(/@/assets/icons/scan-icon/bg.png) 370px 170px no-repeat;
    z-index: auto;
  }

  .tips-success {
    color: green;
    font-size: 18px;
  }

  .tips-error {
    color: red;
    font-size: 18px;
  }
</style>